<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { Game } from '@/types/game';
  import {
    getGameDetail,
    passGame,
    deleteGame,
    publishGame,
    clearMockGame,
  } from '@/api/game';
  import { useRoute, useRouter } from 'vue-router';
  import { Message, Modal } from '@arco-design/web-vue';
  import { GameApproveState } from '@/config/game';
  import GamePreview from '@/views/game/editor/game-preview.vue';
  import ChildGame from '@/views/game/components/child-game.vue';
  import GameProduct from '@/views/game/editor/game-product.vue';
  import GameRefuse from '../components/game-refuse.vue';
  import GamePlay from '../components/game-play/index.vue';
  import GamePlayerScore from '../components/group-player-score/index.vue';
  import GameSignTable from '../components/game-sign-table.vue';
  import GameGroupApp from '../components/game-group/app.vue';
  import SingleReward from '../components/single-reward/index.vue';
  import GameUserMatch from '../components/user-match/index.vue';
  import GameMock from './game-mock.vue';
  import GameRank from '../components/rank/index.vue';

  const route = useRoute();

  const loadingDetail = ref(false);
  const gameInfo = ref<Game | null>(null);

  const initData = async () => {
    try {
      loadingDetail.value = true;

      const gameRes = await getGameDetail(route.query.id as string);
      if (gameRes.data.data.gameProductGroupVOS) {
        gameRes.data.data.gameProductGroupVOS.forEach((group) => {
          group.products.forEach((product) => {
            if (product.rmbPrice) {
              product.rmbPrice /= 100;
            }
          });
        });
      }
      if (gameRes.data.data.caddieFee > 0) {
        gameRes.data.data.caddieFee /= 100;
      }
      gameInfo.value = gameRes.data.data || {};
    } finally {
      loadingDetail.value = false;
    }
  };

  onMounted(() => {
    initData();
  });

  const router = useRouter();
  const handleEditGame = () => {
    router.push({
      name: 'GameEditorApp',
      query: route.query,
    });
  };

  const arraigning = ref(false);
  const handlePassGame = async () => {
    try {
      Modal.confirm({
        title: '提示',
        content: '确定通过该赛事？',
        onOk: async () => {
          await passGame(route.query.id as string);
          Message.success('赛事已通过并发布');
          initData();
        },
      });
    } finally {
      arraigning.value = false;
    }
  };

  const handlePublishGame = async () => {
    Modal.confirm({
      title: '提示',
      content: '确定发布该赛事？',
      onOk: async () => {
        await publishGame(route.query.id as string);
        Message.success('赛事已发布');
        initData();
      },
    });
  };

  const refusing = ref(false);
  const handleRefuseGame = async () => {
    refusing.value = true;
  };
  const handleRefuseDone = async (did: boolean) => {
    if (did) {
      initData();
    }
    refusing.value = false;
  };

  const deleting = ref(false);
  const handleDeleteGame = async () => {
    Modal.confirm({
      title: '确定删除该赛事？',
      content: '删除后无法恢复',
      onOk: async () => {
        await deleteGame(route.query.id as string);
        Message.success('已删除');
        setTimeout(() => {
          window.close();
        }, 2000);
      },
    });
  };

  const wwwUrl = import.meta.env.VITE_WWW_URL;

  const mocking = ref(false);

  const handleClearMock = () => {
    Modal.confirm({
      title: '提示',
      content: '确认执行该操作？',
      async onBeforeOk() {
        await clearMockGame(`${gameInfo.value?.id}`);
      },
    });
  };
</script>

<template>
  <div class="main">
    <a-skeleton v-if="loadingDetail" animation>
      <a-space direction="vertical" :style="{ width: '100%' }" size="large">
        <a-skeleton-line :rows="3" />
        <a-skeleton-shape />
      </a-space>
    </a-skeleton>
    <a-row v-else-if="gameInfo" :gutter="[30, 30]">
      <a-col>
        <div class="approve-header">
          <a-tag
            :color="['gray', 'blue', 'green', 'red'][gameInfo.approveState + 1]"
          >
            {{
              GameApproveState.find((i) => i.value === gameInfo?.approveState)
                ?.label
            }}
          </a-tag>

          <a-space>
            <a-button
              v-if="gameInfo?.gameType === 1 && !gameInfo?.copyFromGameId"
              @click="handleClearMock"
            >
              清除模拟比赛数据
            </a-button>
            <a-button
              v-if="gameInfo?.gameType === 1 && !gameInfo?.copyFromGameId"
              @click="mocking = true"
            >
              模拟比赛
            </a-button>
            <a-link
              :href="`${wwwUrl}/game/score-detail?gameId=${gameInfo?.id}`"
              target="_blank"
            >
              实时成绩链接
            </a-link>

            <a-button
              v-if="gameInfo.approveState === -1 && gameInfo.createFrom === 1"
              @click="handleEditGame"
            >
              编辑
            </a-button>
            <a-button
              v-if="gameInfo.approveState === 0 && gameInfo.createFrom === 2"
              type="primary"
              @click="handlePassGame"
            >
              通过审核
            </a-button>
            <a-button
              v-if="gameInfo.approveState === 0 && gameInfo.createFrom === 2"
              type="primary"
              status="danger"
              @click="handleRefuseGame"
            >
              拒绝通过
            </a-button>
            <a-button
              v-if="gameInfo.approveState === -1 && gameInfo.createFrom === 1"
              type="primary"
              @click="handlePublishGame"
            >
              发布赛事
            </a-button>
            <a-button
              v-if="gameInfo.approveState === -1 && gameInfo.createFrom === 1"
              :loading="deleting"
              status="danger"
              @click="handleDeleteGame"
            >
              删除赛事
            </a-button>
          </a-space>
        </div>

        <a-alert
          v-if="gameInfo.approveState === 2"
          type="warning"
          style="margin-bottom: 20px"
        >
          {{ gameInfo.refuseReason }}
        </a-alert>

        <div class="title">
          <img :src="gameInfo.logo" />
          {{ gameInfo.name }}
        </div>

        <a-steps
          v-if="gameInfo.approveState === 1"
          type="arrow"
          :current="gameInfo.state + 1"
          small
        >
          <a-step>报名前</a-step>
          <a-step>报名中</a-step>
          <a-step>赛前</a-step>
          <a-step>赛中</a-step>
          <a-step>赛后</a-step>
        </a-steps>
      </a-col>

      <a-col>
        <a-tabs destroy-on-hide lazy-load>
          <a-tab-pane key="basic" title="比赛信息">
            <div class="basic-info">
              <div class="basic-info-preview">
                <div>小程序预览</div>
                <div>
                  <GamePreview v-if="gameInfo" :game="gameInfo" />
                </div>
              </div>
              <div class="basic-info-bill">
                <div>下单页预览</div>
                <div>
                  <GameProduct
                    v-if="gameInfo"
                    :parent-id="gameInfo.parentId"
                    :group-list="gameInfo.gameProductGroupVOS || []"
                  />
                </div>
              </div>
            </div>
          </a-tab-pane>
          <a-tab-pane
            key="sign"
            :title="
              gameInfo?.gameType === 1 && gameInfo?.childGameCount === 1
                ? '预报名情况'
                : '报名情况'
            "
          >
            <GameSignTable
              v-if="gameInfo && gameInfo?.state >= 1"
              :game="gameInfo"
              :game-id="route.query.id as string"
              :is-parent-game="gameInfo?.gameType === 1"
            />
            <div
              v-else
              style="
                line-height: 100px;
                color: var(--color-text-3);
                text-align: center;
              "
            >
              还未开始报名
            </div>
          </a-tab-pane>
          <a-tab-pane
            v-if="gameInfo?.gameType === 1"
            key="childGame"
            :title="gameInfo?.childGameCount === 1 ? '分场' : '阶段'"
          >
            <ChildGame :game-info="gameInfo as Game" />
          </a-tab-pane>
          <a-tab-pane
            v-if="gameInfo?.gameType !== 1 && gameInfo?.type === 3"
            key="userMatch"
            title="配对情况"
          >
            <GameUserMatch :game-id="route.query.id as string" />
          </a-tab-pane>
          <a-tab-pane
            v-if="gameInfo?.gameType !== 1 || gameInfo?.childGameCount === 2"
            key="group"
            title="分组情况"
          >
            <GameGroupApp
              v-if="gameInfo?.state >= 1"
              :game-id="route.query.id as string"
              :disable-group="gameInfo?.childGameCount === 2"
            />
            <div
              v-else
              style="
                line-height: 100px;
                color: var(--color-text-3);
                text-align: center;
              "
            >
              还未开始报名
            </div>
          </a-tab-pane>
          <a-tab-pane
            v-if="gameInfo?.gameType === 0 || gameInfo?.gameType === 2"
            key="score"
            title="实时成绩"
          >
            <GamePlayerScore
              v-if="gameInfo?.state >= 3"
              :game-id="`${gameInfo?.id}`"
              :course-id="gameInfo?.course?.id || ''"
            />
            <div
              v-else
              style="
                line-height: 100px;
                color: var(--color-text-3);
                text-align: center;
              "
            >
              比赛还未开始
            </div>
          </a-tab-pane>
          <a-tab-pane key="play" title="玩法和成绩">
            <GamePlay
              v-if="gameInfo"
              :game-id="gameInfo.id"
              :game-info="gameInfo"
              :is-parent="gameInfo.gameType === 1"
            />
          </a-tab-pane>
          <a-tab-pane
            v-if="gameInfo?.gameType === 0 || gameInfo?.gameType === 2"
            key="reward"
            title="单项奖"
          >
            <SingleReward
              v-if="gameInfo"
              :game-id="gameInfo.id"
              :course-id="gameInfo.courseId"
            />
          </a-tab-pane>
          <a-tab-pane
            v-if="gameInfo?.gameType === 0 || gameInfo?.gameType === 2"
            key="rank"
            title="榜单"
          >
            <GameRank v-if="gameInfo" :game-id="gameInfo.id" />
          </a-tab-pane>
        </a-tabs>
      </a-col>
    </a-row>
  </div>

  <GameRefuse
    v-if="refusing"
    :game-id="(route.query.id as string)"
    @close="handleRefuseDone"
  />

  <GameMock
    v-if="mocking && gameInfo"
    :game-info="gameInfo"
    @close="mocking = false"
  />
</template>

<style lang="less" scoped>
  .main {
    width: 1100px;
    margin: 30px auto;
    background: #fff;
    padding: 20px;
    position: relative;
  }

  .approve-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid rgb(var(--gray-2));
  }

  .title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    img {
      max-height: 40px;
      max-width: 40px;
      margin-right: 12px;
    }
    span {
      font-size: 14px;
      font-weight: normal;
      color: var(--color-text-2);
      margin-left: 10px;
    }
  }

  .info-item {
    margin-top: 12px;
    color: #333;
  }

  .basic-info {
    display: flex;
    justify-content: center;
    &-preview,
    &-bill {
      margin-right: 20px;
      width: 375px;
      & > div:first-child {
        font-weight: bold;
        margin-bottom: 10px;
      }
      & > div:last-child {
        background: #f5f5f5;
      }
    }
  }
</style>
